<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" inline>
                <el-row :gutter="10">
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">设 备</div>
                      <v-select-s v-model="query.equipment_id" action="eqList" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">车 间</div>
                      <v-select v-model="query.workshop_id" action="workshopList" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">负责人</div>
                      <v-select-s v-model="query.admin_id" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">执行人</div>
                      <v-select-s v-model="query.member_id" multiple />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">周 期</div>
                      <el-input v-model="query.period" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">周期单位</div>
                      <el-select v-model="query.period_unit" size="mini">
                        <el-option v-for="(item, periodUnitIndex) in plansPeriodUnit" :key="periodUnitIndex" :value="item.value" :label="item.name" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">状 态</div>
                      <el-select v-model="query.status" size="mini">
                        <el-option v-for="(item, statusIndex) in plansStatus" :key="statusIndex" :label="item.name" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">生产线</div>
                      <v-select-s v-model="query.line_id" action="lineList" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">工 位</div>
                      <v-select-s v-model="query.process_id" action="processList" multiple :query="{line_id:query.line_id}" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">专 业</div>
                      <el-select v-model="query.profession" size="mini">
                        <el-option v-for="(item, statusIndex) in plansProfession" :key="statusIndex" :label="item.name" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">基准日期</div>
                      <el-date-picker v-model="query.execute_time" type="datetimerange" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" size="mini" icon="el-icon-search" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" size="mini" icon="el-icon-document-add" @click="addHandler">增加</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-printer" size="mini" @click="dialogTableVisible = true">导出</el-button>
                <el-dialog title="设备资产导出" :visible.sync="dialogTableVisible" width="45%" center>
                  <el-checkbox v-model="checkAll" class="marginLeft20" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="needExport" class="marginLeft20" @change="handleText">
                    <el-checkbox v-for="item in needExportArray" :key="item" class="width73" checked :label="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取 消</el-button>
                    <el-button type="primary" @click="exportHandler">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <div class="buttonBox">
                <el-upload :show-file-list="false" action="" :before-upload="file => workbook(file, {type: 'add'})">
                  <el-button type="primary" size="mini" icon="el-icon-edit">批量导入</el-button>
                </el-upload>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-delete" size="mini" :disabled="!selection.length" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <a class="download" :href="downloadUrl" download="" title="下载"><el-button type="primary" icon="el-icon-download" size="mini">下载模板</el-button></a>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div class="fr">总计划数：{{ total }}，总设备数：{{ eq_count }}，总任务项：{{ task_count }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-table v-loading="loading" :data="planList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" @selection-change="selectionHandler">
        <el-table-column type="index" label="序号" min-width="50px" align="center" />
        <el-table-column type="selection" min-width="50px" align="center" />
        <el-table-column prop="coding" label="编号" width="150px" align="center" />
        <el-table-column prop="equipment_name" label="名称" width="260px" align="center" />
        <el-table-column prop="workshop_name" label="车间" width="100px" align="center" />
        <el-table-column prop="line_name" label="生产线" width="160px" align="center" />
        <el-table-column prop="process_name" label="工位" width="160px" align="center" />
        <el-table-column prop="admin_name" label="负责人" width="100px" align="center" />
        <el-table-column prop="member_list" label="执行人" min-width="200px" align="center" />
        <el-table-column prop="next_date" label="下一个日期" min-width="160px" align="center" />
        <el-table-column prop="period" label="周期" width="60px" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.period }}{{ row.period_unit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80px" align="center">
          <template slot-scope="{ row }">
            <span v-html="row.status_table" />
          </template>
        </el-table-column>
        <el-table-column prop="task_long" label="任务时长（小时）" width="150" align="center" />
        <el-table-column prop="expect_man_minutes" label="预计工时（分钟）" min-width="100%" width="150" align="center" />
        <el-table-column prop="profession" label="专业" width="100%" align="center" />
        <el-table-column v-if="needEngineer" prop="halt" label="停机" width="100%" align="center" />
        <el-table-column v-if="needEngineer" prop="engineer_list" label="工程师" width="200" align="center" />
        <el-table-column v-if="needEngineer" prop="monitor" label="需班长审核" width="200" align="center" />
        <el-table-column v-if="needEngineer" prop="engineer" label="需工程师审核" width="200" align="center" />
        <el-table-column v-if="listHandle" fixed="right" label="操作" width="180" align="center">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="updateHandler(row.id)">编辑</el-button>
            <el-button type="danger" size="mini" @click="confirmDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
    </div>
  </div>
</template>
<script>
import API from '@/api/project1/plan'
import { plansStatus, plansPeriodUnit, plansProfession } from '@/utils/options'
import VSelect from '@/components/select'
import VSelectS from '@/components/select-search'
import xlsx from 'xlsx'
import exportMethod from '@/mixins/export'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'formatDate', 'selectName', 'isNeedEngineer'],
  components: {
    VSelect,
    VSelectS
  },
  mixins: [exportMethod],
  data() {
    return {
      checkAll: true,
      isIndeterminate: true,
      dialogTableVisible: false,
      needExport: [],
      needExportArray: ['编号', '设备编号', '设备名称', '车间', '执行时间', '负责人', '周期', '周期单位', '任务时长', '停机', '状态', '任务', '执行人', '专业'],
      loading: false,
      total: 0,
      query: { page: 1, limit: 15, category_id: 1 },
      planList: [],
      selection: [],
      eq_count: 0,
      task_count: 0,
      plansStatus,
      plansPeriodUnit,
      plansProfession,
      category_id: 1,
      needEngineer: false,
      downloadUrl: '',
      lsData: []
    }
  },
  computed: {
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    }
  },
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()

    if ([2].includes(this.query.category_id)) {
      this.needExportArray.push('预计工时')
    }

    if ([3, 4].includes(this.query.category_id)) {
      this.needExportArray.push('预计工时', '班长', '工程师', '审核工程师', '备件列表')
    }

    if ([4].includes(this.query.category_id)) {
      this.needExportArray.push('润滑方式')
    }
  },
  methods: {
    handleCheckAllChange(val) {
      this.needExport = val ? this.needExportArray : []
      this.isIndeterminate = false
    },
    handleText(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.needExportArray.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.needExportArray.length
    },
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    index() {
      this.loading = true
      this.category_id = Number(this.$route.path.split('/')[2].split('plan')[1])
      this.query.category_id = this.category_id
      API.planList(this.query).then(res => {
        this.total = res.data.data.total

        this.planList = res.data.data.data
        if (res.data.eq_count && res.data.eq_count > 0) {
          this.eq_count = res.data.eq_count
        }
        if (res.data.task_count && res.data.task_count > 0) {
          this.task_count = res.data.task_count
        }
      }).finally(() => {
        this.loading = false
      })
      const urlCategory = ['', '自主点检', '自主维护', '专业维护', '加油润滑', '专业点检', '专业巡检']
      this.downloadUrl = `https://beiqi.aiemtc.com/exl/${urlCategory[this.category_id]}.xlsx`
    },
    exportHandler() {
      if (this.selection.length === 0) {
        this.query.limit = this.total
        this.loading = true
        API.planList(this.query).then(res => {
          this.selection = res.data.data.data
        }).finally(() => {
          this.thisExport()
          this.loading = false
        })
      } else {
        this.thisExport()
      }
    },
    thisExport() {
      const data = []
      const titleObj = {
        'coding': '编号',
        'equipments.coding': '设备编号',
        'equipments.name': '设备名称',
        'workshops.name': '车间',
        'execute_time': '执行时间',
        'admins.name': '负责人',
        'period': '周期',
        'period_unit_out': '周期单位',
        'task_long': '任务时长',
        'halt_out': '停机',
        'status_out': '状态',
        'task_list': '任务',
        'member': '执行人',
        'profession_out': '专业',
        'expect_man_minutes': '预计工时',
        'monitor_out': '班长',
        'engineer_out': '工程师',
        'engineers': '审核工程师',
        'parts_list': '备件列表',
        'lub_out': '润滑方式'
      }

      // 2自主维护 3专业维护 4润滑

      if (this.query.category_id === '2') {
        titleObj.monitor_out = '班长'
      }

      if (['3', '4'].includes(this.query.category_id)) {
        titleObj.parts_list = '备件列表'
        titleObj.monitor_out = '班长'
        titleObj.engineer_out = '工程师'
        titleObj.engineers = '审核工程师'
      }

      if (this.query.category_id === '4') {
        titleObj.lub_out = '润滑方式'
      }
      if (this.needExport.length) {
        const title = []
        for (const key of this.needExport) {
          title.push(key)
        }
        data.push(title)
      } else {
        data.push(Object.values(titleObj))
      }
      const excelNeedExport = []
      for (const keys of this.needExport) {
        const thisKey = Object.keys(titleObj).find(key => titleObj[key] === keys)
        excelNeedExport.push(thisKey)
      }
      let fieldOut = 1

      // item是循环的数组，就是每一行数据，
      this.selection.forEach((item) => {
        if (excelNeedExport.length) {
          const d = []
          // key是每一个字段，excelNeedExport是一个集合，一个页面上勾选汉字（value）所对应的英文（key）
          for (const key of excelNeedExport) {
            if (key.includes('.')) {
              let value = item
              const tag = key.split('.')
              for (const k of tag) {
                value = value[k]
              }
              d.push(value)
            } else {
              d.push(item[key])
            }
          }
          data.push(d)
        } else {
          this.$message.error('请选择要到导出的字段')
          fieldOut = 2
        }
      })
      if (fieldOut === 1) {
        const workbook = {
          SheetNames: ['plan1'],
          Sheets: {
            'plan1': xlsx.utils.aoa_to_sheet(data)
          }
        }
        const titleArr = ['', '自主点检', '自主维护', '专业维护', '加油润滑', '专业点检', '专业巡检']
        const excelName = titleArr[this.query.category_id]
        this.exportExec(workbook, `${excelName}计划.xlsx`)
        this.reload()
      }
    },
    remove() {
      this.setStorage()
      const selection = this.selection
      this.delMany(API, selection)
    },
    confirmDel(id) {
      this.setStorage()
      this.delOne(API, id, false)
    },
    periodFormat(row) {
      return row.period + this.selectName(plansPeriodUnit, row.period_unit)
    },
    addHandler() {
      this.setStorage()
      this.goUrl(`/project1/plan${this.query.category_id}/plan_add`)
    },
    updateHandler(id) {
      this.setStorage()
      const url = `/project1/plan${this.query.category_id}/plan_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    workbook(file, type) {
      const reader = new FileReader()
      const self = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = xlsx.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        const postData = {}
        postData.outData = outData
        postData.type = type['type']
        postData.planCategory = self.query.category_id
        API.excel(postData).then(response => {
          if (response.data.error_code === 1) {
            const text = postData.type === 'add' ? '导入成功' : '更新成功'
            self.$message.success(`恭喜你，${text}`)
            self.reload()
          } else {
            self.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    setStorage() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
    }
  }
}
</script>
